
package com.wish.wishsystem_management.service.impl;



import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.wishsystem_management.entity.TbSmsRecords;
import com.wish.wishsystem_management.mapper.TbSmsRecordsMapper;
import com.wish.wishsystem_management.service.ISysUserService;
import com.wish.wishsystem_management.service.ITbSmsRecordsService;
import dto.systemDto.SysUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import vo.ResultEntity;

import java.util.Collection;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 短信记录 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-03-28
 */
@Slf4j
@Service
public class TbSmsRecordsServiceImpl extends ServiceImpl<TbSmsRecordsMapper, TbSmsRecords> implements ITbSmsRecordsService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ISysUserService iSysUserService;

    /**
     *  code码
     *      200 成功  ,  3001 号码已存在  ,  3002 验证短信未超过两分钟
     * @param dto
     * @return
     */
    @Override
    public ResultEntity sendSms(SysUserDto dto) {
//        String mobile = dto.getMobile();
        //  判断是否存在手机号
//        SysUser user = iSysUserService.findByMobile(mobile);
//        if (user!=null){
//            log.info("号码已存在,直接返回");
//            return ResultEntity.error("3001","号码已存在",null);
//        }
        // 查看短信验证码是否超过2分钟
        String s = this.sendMobileCode();
        if (s.equals("3002")){
            return ResultEntity.error("3002","验证短信未超过两分钟",null);
        }
        log.info("短信验证码为==>{}",s);

        return ResultEntity.ok();
    }

    /**
     *  通过reids 判断存入的key是否过期  从而判断是否在2分钟重新发送过短信
     * @return
//     */
//    public String sendMobileCode(){
//        log.info("是否发送短信验证开始==>>{}","start");
//        StringBuffer sb = new StringBuffer();
//        for(int i = 0; i<6;i++){
//            sb.append((int)(Math.random()*10));
//        }
//        ValueOperations ops = redisTemplate.opsForValue();
//        if (redisTemplate.hasKey("code")){
//            log.info("验证短信未超过两分钟");
//            return "3002";
//        }else{
//            ops.set("code",sb,2, TimeUnit.MINUTES);
//            return String.valueOf(sb);
//        }
//    }

    public String sendMobileCode(){
        log.info("是否发送短信验证开始==>>{}","start");
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i<6;i++){
            sb.append((int)(Math.random()*10));
        }
        ValueOperations ops = redisTemplate.opsForValue();
        if (redisTemplate.hasKey("code")){
            log.info("验证短信未超过两分钟");
            return "3002";
        }else{
            ops.set("code",sb,2, TimeUnit.MINUTES);
            return String.valueOf(sb);
        }
    }


}
